import os
import sys

from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import QApplication, QWidget, \
    QVBoxLayout, QHBoxLayout, QComboBox, QPushButton, QLineEdit, QFileDialog, QTableView

from workspace.Project.LogParse.py_presenter_log import PresenterComponentLog
from workspace.Project.UI.components.py_ui_abstract_log import InterfaceOfComponentLog
from workspace.Project.UI.components.py_ui_component_log_cfg import UiComponentLogCfgForm
from workspace.Project.UI.ui_base.py_ui_abstract import AbstractUiView


class UiComponentLog(AbstractUiView, InterfaceOfComponentLog):
    signal_component_log = pyqtSignal(object)

    def hideEvent(self, event):
        try:
            self.filter_view.hide()  # 关闭挂在自己窗体下的子窗体
            print("隐藏日志子界面")
        except:
            print("没有日志子界面")
            pass
        event.accept

    def closeEvent(self, event):
        print("关闭日志界面")
        try:
            self.filter_view.close()  # 关闭挂在自己窗体下的子窗体
        except:
            pass
        event.accept()

    def __init__(self, cwd):
        super(UiComponentLog, self).__init__(ui_name='ui_component_log', ui_version='v1.0.0')
        self._set_ui()
        self._cwd = cwd
        self.presenter = PresenterComponentLog(self)  # VP交互的1.2 实例化P处理逻辑 传递V到P
        self.filter_view = UiComponentLogCfgForm(self._cwd)
        self.filter_view.signal_ui_log_cfg.connect(self._slot_get_filter_cfg)
        self._filter_select = None

    def _set_ui(self):
        self._create_operate()
        self._create_result()

        main_layout = QVBoxLayout()
        main_layout.addWidget(self.op_widget)
        main_layout.addWidget(self.re_widget)
        self.setLayout(main_layout)

    def _create_operate(self):
        self.op_widget = QWidget()
        op_layout = QHBoxLayout()
        self.cb_file_type = QComboBox()
        self.cb_file_type.addItems(['文本文件', '多文本文件', '文件夹', '压缩包'])
        self.cb_show_type = QComboBox()
        self.cb_show_type.addItems(['表格', '图形'])
        self.bt_match_cfg = QPushButton('筛选配置')
        self.bt_match_cfg.clicked.connect(self._open_match_cfg_show_form)
        self.bt_select_target = QPushButton('选择目标文件')
        self.bt_select_target.clicked.connect(self._select_target_file_dialog)
        self.le_target_path = QLineEdit()
        self.le_target_path.setPlaceholderText('文件路径')
        self.bt_result_output = QPushButton('结果导出')
        # self.bt_result_output.clicked.connect(self._result_output_dialog)

        op_layout.addWidget(self.cb_file_type)
        op_layout.addWidget(self.cb_show_type)
        op_layout.addWidget(self.bt_match_cfg)
        op_layout.addWidget(self.bt_select_target)
        op_layout.addWidget(self.le_target_path)
        op_layout.addWidget(self.bt_result_output)

        self.op_widget.setLayout(op_layout)

    def _create_result(self):
        self.re_widget = QWidget()
        re_layout = QVBoxLayout()
        # 设置tableview 控件
        self.header_list = ['日期']
        self.item_model = QStandardItemModel()
        self.item_model.setHorizontalHeaderLabels(self.header_list)
        self.tableview_log = QTableView()
        self.tableview_log.setModel(self.item_model)
        re_layout.addWidget(self.tableview_log)
        self.re_widget.setLayout(re_layout)

    def _select_target_file_dialog(self):
        openfile_path, filetype = QFileDialog.getOpenFileName(self, '打开文件', self._cwd, "Text Files (*.txt)")
        filter_info = {
            'filter_type': 'repaint',
            'filter_file_path': openfile_path,
            'filter_file_type': filetype,
            'filter_cfg_info': self._filter_select
        }
        self.presenter.interface_presenter_input_filter_info(filter_info=filter_info)

    def interface_log_fiter_update(self, **kwargs):
        if 'header_list' in kwargs:
            # print(kwargs.get('header_list'))
            self._tableview_update(header_list=kwargs.get('header_list'))

        if 'data_info' in kwargs:
            # print(kwargs.get('data_info'))
            self._tableview_update(data_info=kwargs.get('data_info'))

    def _tableview_update(self, **kwargs):
        if 'header_list' in kwargs:
            self.tableview_header = kwargs.get('header_list')
            self.item_model.setHorizontalHeaderLabels(self.tableview_header)

        if 'data_info' in kwargs:
            self.item_model.clear()
            self.item_model.setHorizontalHeaderLabels(self.tableview_header)
            for info in kwargs['data_info']:
                items_row = []
                for key in info:
                    items_row.append(QStandardItem(str(info[key])))
                self.item_model.appendRow(items_row)

    # 实现子窗体的功能
    def _open_match_cfg_show_form(self):
        # self.filter_view.exec()
        self.filter_view.show()

    def interface_log_fiter_cfg_update(self, **kwargs):
        # 通过P层返回的数据，更新子窗体
        if 'header_list' in kwargs:
            # print(kwargs.get('header_list'))
            self.filter_view.update_match_tableview(header_list=kwargs.get('header_list'))
        if 'data_info' in kwargs:
            # print(kwargs.get('data_info'))
            self.filter_view.update_match_tableview(data_info=kwargs.get('data_info'))

    def _slot_get_filter_cfg(self, filter_cfg):
        # 接收子窗体的信号,进行分发逻辑
        if 'Event' in filter_cfg:
            self.signal_component_log.emit(filter_cfg)
        if 'filter_cfg' in filter_cfg:  # 文件类型的操作
            self.presenter.interface_presenter_input_filter_cfg_info(filter_cfg=filter_cfg['filter_cfg'])
        if 'filter_select' in filter_cfg:  # 选择的过滤配置
            self._filter_select = filter_cfg['filter_select']
            print(self._filter_select)
            # self.presenter.interface_presenter_input_filter_info()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app_path = os.getcwd()
    main = UiComponentLog(app_path)
    main.show()
    sys.exit(app.exec())
